package com.qianclass.talklive.app.screenshots;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.net.Uri;
import android.view.Display;
import android.view.View;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * 获取和保存当前屏幕的截图
 */
public class ScreenShot {

    public static boolean shoot(Activity activity, File filePath, Context context) {
        boolean isSuccess = false;
        if (filePath == null) {
            return false;
        }
        if (!filePath.getParentFile().exists()) {
            filePath.getParentFile().mkdirs();
        }
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(filePath);
            if (null != fos) {
                myShot(activity).compress(Bitmap.CompressFormat.PNG, 100, fos);
                isSuccess = true;
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            isSuccess = false;
        } finally {
            if (fos != null) {
                try {
                    fos.flush();
                    fos.close();
                    //保存图片后发送广播通知更新数据库
                    Uri uri = Uri.fromFile(filePath);
                    context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
                } catch (IOException e) {
                    e.printStackTrace();
                    isSuccess = false;
                }
            }
        }
        return isSuccess;
    }


    //获取Bitmap格式的屏幕截图
    public static Bitmap myShot(Activity activity) {
        // 获取windows中最顶层的view
        View view = activity.getWindow().getDecorView();
        view.buildDrawingCache();

        // 获取状态栏高度
        Rect rect = new Rect();
        view.getWindowVisibleDisplayFrame(rect);
        int statusBarHeights = rect.top;
        Display display = activity.getWindowManager().getDefaultDisplay();

        // 获取屏幕宽和高
        int widths = display.getWidth();
        int heights = display.getHeight();

        // 允许当前窗口保存缓存信息
        view.setDrawingCacheEnabled(true);

        // 去掉状态栏
        Bitmap bmp = Bitmap.createBitmap(view.getDrawingCache(), 0,
                statusBarHeights, widths, heights - statusBarHeights);

        // 销毁缓存信息
        view.destroyDrawingCache();

        return bmp;
    }


}
